<?php

namespace App\Models;

use App\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Model;

class WithdrawalLog extends Model
{
    protected $table ="c_withdrawal_logs";

    public function adminuser()
    {
        return $this->hasOne('App\Models\AdminUser','id','operation_uid');
    }


    /***
     *
     * 添加提现记录
     *
     */
    public function add($filter)
    {

        try {
            DB::beginTransaction(); // 开始事务
            $this->user_id = $filter['user_id'];
            $this->type = $filter['type'];
            $this->money = $filter['money'];
            $this->name = $filter['name'];
            $this->surplus = $filter['surplus'];
            $this->alipay_account = $filter['alipay_account'];
            $this->alipay_name = $filter['alipay_name'];
            $this->is_deposit = isset($filter['is_deposit'])?$filter['is_deposit']:0;
            $this->deposit_surplus = isset($filter['deposit_surplus'])?$filter['deposit_surplus']:0;
            $data = $this->save();
            if ($data) {
                if ($filter['type'] == 1) {
                    if(isset($filter['is_deposit']) && $filter['is_deposit'] == 1){
                       (new DoctorWorks())->where([['id', '=', $filter['user_id']]])->decrement("deposit_surplus", $filter['money']);
                    }
                    $reda = (new DoctorWorks())->where([['id', '=', $filter['user_id']]])->decrement("surplus", $filter['money']);
                } elseif ($filter['type'] == 2) {
                    $reda = (new User())->where([['id', '=', $filter['user_id']]])->decrement("surplus", $filter['money']);
                }
                if ($reda) {
                    DB::commit(); // 提交事务
                    return true;
                } else {
                    return false;
                    DB::rollback(); // 回滚事务
                }
            }
        } catch (Exception $e) {
            DB::rollback(); // 回滚事务
        }
    }

    /***
     * 获取提现记录
     */
    public function getWithdrawalLog($filter)
    {
        if(isset($filter['status'])){
            return self::where([['type','=',1],['user_id','=',$filter['work_id']],['status','=',$filter['status']]])->select("money","status","back_reason","surplus","name","created_at","alipay_account","alipay_name","operation_time","is_deposit","deposit_surplus")->orderBy("id","desc")->get();
        }
       return self::where([['type','=',1],['user_id','=',$filter['work_id']]])->select("money","status","status","back_reason","surplus","name","created_at","alipay_account","alipay_name","operation_time","is_deposit","deposit_surplus")->orderBy("id","desc")->get();
    }
}
